/*   
 * Copyright 2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.util;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;

import javax.naming.NamingEnumeration;

import org.w3c.dom.NodeList;

public class ForEach {

    @SuppressWarnings("unchecked")
    public static void forEach(Collection c, AnonymousFunction f) {
        for (Object item : c) {
            f.fn(item);
        }
    }


    @SuppressWarnings("unchecked")
    public static void forEach(Iterator c, AnonymousFunction f) {
        while (c.hasNext()) {
            Object item = c.next();
            f.fn(item);
        }
    }


    @SuppressWarnings("unchecked")
    public static void forEach(Enumeration c, AnonymousFunction f) {
        while (c.hasMoreElements()) {
            Object item = c.nextElement();
            f.fn(item);
        }
    }


    @SuppressWarnings("unchecked")
    public static void forEach(Object[] array, AnonymousFunction f) {

        for (int i = 0; array != null && i < array.length; i++) {
            f.fn(array[i]);
        }
    }


    @SuppressWarnings("unchecked")
    public static void forEach(NodeList nl, AnonymousFunction f) {
        for (int i = 0; i < nl.getLength(); i++) {
            f.fn(nl.item(i));
        }
    }


    @SuppressWarnings("unchecked")
    public static void forEach(ResultSet rs, AnonymousFunction f)
            throws SQLException {
        while (rs.next()) {
            f.fn(rs);
        }
    }


    @SuppressWarnings("unchecked")
    public static void forEach(NamingEnumeration ne, AnonymousFunction f) {
        while (ne.hasMoreElements()) {
            f.fn(ne.nextElement());
        }
    }

}
